package com.example.cr.insect.service;

import com.example.cr.insect.dto.ChartDataDTO;
import com.example.cr.insect.entity.Farm;
import com.example.cr.insect.entity.PestFrequency;
import com.example.cr.insect.repository.PestFrequencyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ChartService {

    private static final String[] CHINESE_MONTHS = {"一月", "二月", "三月", "四月", "五月", "六月",
            "七月", "八月", "九月", "十月", "十一月", "十二月"};

    @Autowired
    private PestFrequencyRepository repository;

    public ChartDataDTO getChartData() {
        List<PestFrequency> records = repository.findAllWithFarm();
        Map<Farm, List<Integer>> farmData = new LinkedHashMap<>();

        // 初始化月份
        List<String> months = Arrays.asList(CHINESE_MONTHS);

        // 按农场分组数据
        for (PestFrequency pf : records) {
            Farm farm = pf.getFarm();
            farmData.putIfAbsent(farm, new ArrayList<>(Collections.nCopies(12, 0)));
            if (pf.getMonth() >= 1 && pf.getMonth() <= 12) {
                farmData.get(farm).set(pf.getMonth() - 1, pf.getValue());
            }
        }

        // 构建series
        List<ChartDataDTO.SeriesDTO> series = new ArrayList<>();
        for (Map.Entry<Farm, List<Integer>> entry : farmData.entrySet()) {
            ChartDataDTO.SeriesDTO dto = new ChartDataDTO.SeriesDTO();
            dto.setName(entry.getKey().getName());
            dto.setData(entry.getValue());
            series.add(dto);
        }

        ChartDataDTO result = new ChartDataDTO();
        result.setMonths(months);
        result.setSeries(series);
        return result;
    }
}